from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template


@index_blu.route('/news_list')
def news_list():
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', 10)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    # filters = [News.status == 0]
    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    #  当前页数
    current_page = paginate.page
    #  总页数
    total_page = paginate.pages
    #  当前页的数据
    news_list_dict = paginate.items

    news_list_dict = [news.to_basic_dict() for news in news_list_dict]

    #  新闻数据
    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list_dict': news_list_dict
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@index_blu.route('/')
@user_login_data
def index():
    # 判断是否有已经登陆过
    user = g.user
    news_dict = []
    try:
        news_dict = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as ret:
        print(ret)
        news_dict = [news.to_basic_dict() for news in news_dict]
    #  查询新闻分类
    category_list = []
    try:
        category_list = Category.query.all()
    except Exception as ret:
            current_app.logger.error(ret)
    category_list = [category.to_dict() for category in category_list]
    #  如果登陆过则查询到用户 返回数据
    data = {
        'user': user.to_dict() if user else None,
        'news_dict': news_dict,
        'category_list': category_list
    }
    #  模板文件找的是创建app文件的同级目录templates内的文件
    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
# 打网页的时候浏览器默认会请求静态文件夹static+favicon.ico做网站标签的小图标
def favicon():
    return current_app.send_static_file('news/favicon.ico')



